package com.academic.system.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.academic.system.controller.request.CreateUserRequest;
import com.academic.system.controller.request.UpdateProfileRequest;
import com.academic.system.controller.request.UpdateUserRequest;
import com.academic.system.model.User;
import com.academic.system.model.UserRole;
import com.academic.system.service.UserService;

/**
 * 用户管理控制器
 */
@RestController
@RequestMapping("/api/users")
@CrossOrigin(origins = "*", maxAge = 3600)
public class UserController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    /**
     * 创建新用户
     */
    @PostMapping("/create")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> createTeacher(@Valid @RequestBody CreateUserRequest request) {
        // 检查用户名是否已存在
        if (userService.findByUsername(request.getUsername()) != null) {
            return ResponseEntity
                .status(HttpStatus.BAD_REQUEST)
                .body(Map.of("message", "用户名已存在"));
        }
        
        // 创建新用户
        User newUser = new User();
        newUser.setUsername(request.getUsername());
        newUser.setPassword(passwordEncoder.encode(request.getPassword()));
        newUser.setRealName(request.getRealName());
        newUser.setRole(UserRole.TEACHER); // 只允许管理员创建教师
        newUser.setDepartment(request.getDepartment());
        newUser.setEmail(request.getEmail());
        newUser.setStatus(1); // 启用
        
        User savedUser = userService.createUser(newUser);
        
        // 构造响应，不返回密码
        Map<String, Object> response = new HashMap<>();
        response.put("id", savedUser.getId());
        response.put("username", savedUser.getUsername());
        response.put("realName", savedUser.getRealName());
        response.put("role", savedUser.getRole());
        response.put("createdAt", savedUser.getCreatedAt());
        
        return ResponseEntity.status(HttpStatus.CREATED).body(response);
    }
    
    /**
     * 获取所有教师
     */
    @GetMapping("/teachers")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> getAllTeachers() {
        List<User> teachers = userService.findAllTeachers();
        List<Map<String, Object>> result = teachers.stream()
            .map(this::convertToDto)
            .collect(Collectors.toList());
        
        return ResponseEntity.ok(result);
    }
    
    /**
     * 根据ID获取用户
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN') or hasRole('TEACHER')")
    public ResponseEntity<?> getUserById(@PathVariable Integer id) {
        User user = userService.findById(id);
        if (user != null) {
            return ResponseEntity.ok(convertToDto(user));
        } else {
            return ResponseEntity
                .status(HttpStatus.NOT_FOUND)
                .body(Map.of("message", "用户不存在"));
        }
    }
    
    /**
     * 更新用户信息
     */
    @PutMapping("/update")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> updateUser(@Valid @RequestBody UpdateUserRequest request) {
        User user = userService.findById(request.getId());
        if (user == null) {
            return ResponseEntity
                .status(HttpStatus.NOT_FOUND)
                .body(Map.of("message", "用户不存在"));
        }
        
        // 更新用户信息
        if (request.getRealName() != null) {
            user.setRealName(request.getRealName());
        }
        
        if (request.getEmail() != null) {
            user.setEmail(request.getEmail());
        }
        
        if (request.getDepartment() != null) {
            user.setDepartment(request.getDepartment());
        }
        
        // 如果提供了新密码，则更新密码
        if (request.getNewPassword() != null && !request.getNewPassword().isEmpty()) {
            user.setPassword(passwordEncoder.encode(request.getNewPassword()));
        }
        
        User updatedUser = userService.updateUser(user);
        
        return ResponseEntity.ok(convertToDto(updatedUser));
    }
    
    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> deleteUser(@PathVariable Integer id) {
        User user = userService.findById(id);
        if (user == null) {
            return ResponseEntity
                .status(HttpStatus.NOT_FOUND)
                .body(Map.of("message", "用户不存在"));
        }
        
        userService.deleteUser(id);
        
        return ResponseEntity.ok(Map.of("message", "用户已删除"));
    }
    
    /**
     * 获取当前用户个人信息
     */
    @GetMapping("/profile")
    @PreAuthorize("hasRole('ADMIN') or hasRole('TEACHER') or hasRole('STUDENT')")
    public ResponseEntity<?> getCurrentUserProfile(HttpSession session) {
        try {
            // 从Session中获取当前用户信息
            User currentUser = (User) session.getAttribute("currentUser");
            if (currentUser == null) {
                return ResponseEntity
                    .status(HttpStatus.UNAUTHORIZED)
                    .body(Map.of("message", "用户未登录"));
            }
            
            // 重新从数据库获取最新的用户信息
            User user = userService.findById(currentUser.getId());
            if (user == null) {
                return ResponseEntity
                    .status(HttpStatus.NOT_FOUND)
                    .body(Map.of("message", "用户不存在"));
            }
            
            return ResponseEntity.ok(convertToDto(user));
        } catch (Exception e) {
            return ResponseEntity
                .status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(Map.of("message", "获取用户信息失败", "error", e.getMessage()));
        }
    }
    
    /**
     * 更新当前用户个人信息
     */
    @PutMapping("/profile")
    @PreAuthorize("hasRole('ADMIN') or hasRole('TEACHER') or hasRole('STUDENT')")
    public ResponseEntity<?> updateProfile(@Valid @RequestBody UpdateProfileRequest request, 
                                         HttpSession session) {
        try {
            // 从Session中获取当前用户信息
            User currentUser = (User) session.getAttribute("currentUser");
            if (currentUser == null) {
                return ResponseEntity
                    .status(HttpStatus.UNAUTHORIZED)
                    .body(Map.of("message", "用户未登录"));
            }
            
            // 获取数据库中的用户信息
            User user = userService.findById(currentUser.getId());
            if (user == null) {
                return ResponseEntity
                    .status(HttpStatus.NOT_FOUND)
                    .body(Map.of("message", "用户不存在"));
            }
            
            // 如果要修改密码，先验证当前密码
            if (request.getNewPassword() != null && !request.getNewPassword().isEmpty()) {
                if (request.getCurrentPassword() == null || request.getCurrentPassword().isEmpty()) {
                    return ResponseEntity
                        .status(HttpStatus.BAD_REQUEST)
                        .body(Map.of("message", "修改密码时必须提供当前密码"));
                }
                
                if (!passwordEncoder.matches(request.getCurrentPassword(), user.getPassword())) {
                    return ResponseEntity
                        .status(HttpStatus.BAD_REQUEST)
                        .body(Map.of("message", "当前密码不正确"));
                }
                
                if (!request.getNewPassword().equals(request.getConfirmPassword())) {
                    return ResponseEntity
                        .status(HttpStatus.BAD_REQUEST)
                        .body(Map.of("message", "新密码与确认密码不一致"));
                }
                
                user.setPassword(passwordEncoder.encode(request.getNewPassword()));
            }
            
            // 更新基本信息（只允许用户修改自己的基本信息，不能修改用户名、角色等敏感信息）
            if (request.getRealName() != null && !request.getRealName().trim().isEmpty()) {
                user.setRealName(request.getRealName().trim());
            }
            
            if (request.getPhone() != null && !request.getPhone().trim().isEmpty()) {
                user.setPhone(request.getPhone().trim());
            }
            
            if (request.getEmail() != null && !request.getEmail().trim().isEmpty()) {
                user.setEmail(request.getEmail().trim());
            }
            
            if (request.getDepartment() != null && !request.getDepartment().trim().isEmpty()) {
                user.setDepartment(request.getDepartment().trim());
            }
            
            // 更新用户信息
            User updatedUser = userService.updateUser(user);
            
            // 更新Session中的用户信息
            session.setAttribute("currentUser", updatedUser);
            
            Map<String, Object> response = new HashMap<>();
            response.put("message", "个人信息更新成功");
            response.put("user", convertToDto(updatedUser));
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            return ResponseEntity
                .status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(Map.of("message", "更新个人信息失败", "error", e.getMessage()));
        }
    }
    
    /**
     * 将用户实体转换为DTO
     */
    private Map<String, Object> convertToDto(User user) {
        Map<String, Object> dto = new HashMap<>();
        dto.put("id", user.getId());
        dto.put("username", user.getUsername());
        dto.put("realName", user.getRealName());
        dto.put("role", user.getRole());
        dto.put("department", user.getDepartment());
        dto.put("phone", user.getPhone());
        dto.put("email", user.getEmail());
        dto.put("createdAt", user.getCreatedAt());
        dto.put("lastLogin", user.getLastLogin());
        dto.put("status", user.getStatus());
        
        return dto;
    }
} 